package com.my.algorithmlearning.leetcode.slidewindow;

import org.springframework.util.Assert;

/**
 * @ClassName Medium_3_LongestSubstringWithoutRepeatingCharacters
 * @Description 题目：https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-interview-150
 * @Author wanghaiwei
 * @Date 2024-04-19
 */
public class Medium_3_LongestSubstringWithoutRepeatingCharacters {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        int i = 0;
        int j = 0;
        int maxLength = 1;
        while(i < s.length() && j < s.length()) {
            int idxOfRepeatChar = findIdxOfRepeatChar(i, j+1, s);
            if (idxOfRepeatChar >= 0) {
                maxLength = Math.max(maxLength, getLength(j, i));
                i = idxOfRepeatChar + 1;
                j++;
            }else if (j == (s.length() - 1)) {
                maxLength = Math.max(maxLength, getLength(j, i));
                break;
            }else {
                maxLength = Math.max(maxLength, getLength(j+1, i));
                j++;
            }
        }
        return maxLength;
    }

    private static int getLength(int j, int i) {
        return j - i + 1;
    }

    private int findIdxOfRepeatChar(int begin, int targetCharIdx, String s) {
        if (targetCharIdx >= s.length()) {
            return -1;
        }
        int idx = begin;
        char targetChar = s.charAt(targetCharIdx);
        while(idx < targetCharIdx) {
            if(s.charAt(idx) == targetChar) {
                return idx;
            }
            idx++;
        }
        return -1;
    }

    public static void main(String[] args) {
        Medium_3_LongestSubstringWithoutRepeatingCharacters solution = new Medium_3_LongestSubstringWithoutRepeatingCharacters();
        int length = solution.lengthOfLongestSubstring("abcabcbb");
        Assert.isTrue(length == 3, "abcabcbb计算错误，预期是3，实际是" + length);

        length = solution.lengthOfLongestSubstring("bbbbb");
        Assert.isTrue(length == 1, "bbbbb计算错误，预期是1，实际是" + length);

        length = solution.lengthOfLongestSubstring("au");
        Assert.isTrue(length == 2, "au计算错误，预期是2，实际是" + length);
    }
}
